<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useHistoryAPI } from "@/services/history";
import { IconPlay, IconHeart } from "@/components/icons";
import { ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user";
import { usePlayerStore } from "@/stores/player";
import SongList from "@/components/SongList.vue";
const userStore = useUserStore();
const playerStore = usePlayerStore();

interface Song {
  id: number;
  title: string;
  artist: string;
  duration: string;
}

interface HistoryRecord {
  id: number;
  userId: string;
  musicId: string;
  createTime: string;
  musicName: string;
  musicAuthor: string;
  musicCoverUrl: string;
  musicUrl: string;
  musicLength: string;
  isFavorite: boolean;
  musicAlbum: string;
  musicAverageGrade: string;
}

const currentPage = ref(1);
const pageSize = ref(15);
const recentSongs = ref<HistoryRecord[]>([]);
const historyCount = ref(0);
const loading = ref(true);
const { getPlayHistoryPage } = useHistoryAPI();

const loadHistoryRecords = async () => {
  try {
    const res = await getPlayHistoryPage(
      userStore.uid,
      currentPage.value,
      pageSize.value
    );
    if (res.code === 200) {
      recentSongs.value = res.data.items.map((item: any) => ({
        id: item.musicId,
        name: item.musicName,
        artist: item.musicAuthor,
        url: item.musicUrl,
        cover: item.musicCoverUrl,
        length: item.musicLength,
        status: item.status,
        album: item.musicAlbum,
        score: item.musicAverageScore,
        lyric: item.lyric,
        isFavorite: item.isFavorite,
      }));

      historyCount.value = res.data.total;
    }
  } catch (error) {
    console.error("获取历史记录失败:", error);
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  await loadHistoryRecords();
});

const clearPlayHistory = async () => {
  try {
    await ElMessageBox.confirm("确定要清空播放历史记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // TODO: 清空历史记录接口
  } catch {
    // 用户取消操作
  }
};

const handleCurrentChange = async (page: number) => {
  currentPage.value = page;
  await loadHistoryRecords();
};

const handleSizeChange = async (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  await loadHistoryRecords();
};

const playAll = () => {
  if (recentSongs.value.length > 0) {
    playerStore.playSong(recentSongs.value[0], recentSongs.value);
  }
};
</script>

<template>
  <div class="p-4" v-if="!loading">
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-lg font-bold">
        最近播放
        <span class="text-sm text-gray-500 font-normal">
          共{{ historyCount }}首
        </span>
      </h2>
      <!-- <button
        class="px-3 py-1 text-sm text-gray-400 hover:text-red-600 rounded"
        @click="clearPlayHistory"
      >
        清空列表
      </button> -->
    </div>
    <div class="mb-4">
      <button
        class="flex items-center gap-2 px-4 py-2 bg-gray-200 text-gray-900 rounded hover:bg-gray-300 text-sm"
        @click="playAll"
      >
        <IconPlay class="w-5 h-5" />
        <span>播放全部</span>
      </button>
    </div>

    <SongList :songs="recentSongs" :show-header="false" />

    <div class="flex justify-center mt-4">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="historyCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
      />
    </div>
  </div>
</template>

<style scoped>
:deep(.el-table) {
  --el-table-border-color: transparent;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-hover-bg-color: #f9fafb;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__cell) {
  border-bottom: none;
}

:deep(.el-table__row) {
  border-radius: 8px;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
}
</style>
